import { WeaSearchGroup, WeaFormItem, WeaDatePicker, WeaTimePicker, WeaTools, WeaAlertPage, WeaUpload, WeaProgress, WeaRichText, WeaLocaleProvider } from 'ecCom';
import { Button, Row, Col, InputNumber, Modal, message } from 'antd';
import { toJS } from "mobx"
import { WeaSwitch } from "comsMobx"
import { inject, observer } from 'mobx-react';
import PrjDateTime from '../comp/prj-data-time'
import { datediff } from '../../util/index'
import { isUndefined } from 'util';
const getKey = WeaTools.getKey;
const getLabel = WeaLocaleProvider.getLabel;
const view_basicToolBar = {
    uploadUrl: "/api/blog/fileupload/uploadimage", 
    startupFocus: false,
    toolbar: [],
};

const basicToolBar = {
    uploadUrl: "/api/blog/fileupload/uploadimage", 
    startupFocus: false,
    toolbar: [
        { name: 'markdown', items: ['Markdown'] },
        { name: 'document', items: ['Source', '-', 'Save', 'NewPage', 'Preview', '-', 'Templates'] },
        { name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] },
        { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'CopyFormatting', 'RemoveFormat'] },
        { name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize'] },
        { name: 'colors', items: ['TextColor', 'BGColor'] },
        { name: 'tools', items: ['Maximize', 'ShowBlocks'] },
        { name: 'insert', items: ['Image', 'Table', 'Smiley'] }
    ],
};

@observer
export default class TaskInfo extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            stageVisiable : 3
        }
    }

    render() {
        const { taskInfo, setFormFields, setValidate, fieldinfo, isTimeShow } = this.props.listStore;
        const { form } = this.props;
        const { isFormInit } = form;
        let group = [];
        const formParams = form.getFormParams();
        isFormInit && fieldinfo.map((c,i) => {
            let items = [];
            c.items.map(fields => {
                let hide = false;
                let dom;
                let hasunderline = false;
                //只读样式控制
                let stylecss = { 'margin-right': '5px', 'margin-top': '6px' };
                if (fields.viewAttr == "1" || (fields.conditionType == "BROWSER" && fields.browserConditionParam.viewAttr == "1")) {
                    hasunderline = true;
                    stylecss = { 'margin-right': '5px', 'margin-top': '16px' };
                }
                if (fields.domkey[0] == "begindate") {
                    dom = <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@gh6xl8@${fields.domkey[0]}`}>
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@2mjr68@${fields.domkey[0]}`} span={24} style={stylecss}>
                            <PrjDateTime ecId={`${this && this.props && this.props.ecId || ''}_PrjDateTime@kuovcm@${fields.domkey[0]}`}
                                {...fields}
                                isTimeShow={isTimeShow}
                                type='start'
                                endValue={formParams.enddate ? new Date(formParams.enddate) : null}
                                value={[formParams.begindate, formParams.begintime]}
                                onChange={(v) => { setFormFields({ begindate__begintime: { value: v } }); this.workdayComputed(v, "begin") }} />
                        </Col>
                    </Row>
                } else if (fields.domkey[0] == "enddate") {
                    dom = <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@p72lhi@${fields.domkey[0]}`}>
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@r6pjjd@${fields.domkey[0]}`} span={24} style={stylecss}>
                            <PrjDateTime ecId={`${this && this.props && this.props.ecId || ''}_PrjDateTime@dydyss@${fields.domkey[0]}`}
                                {...fields}
                                isTimeShow={isTimeShow}
                                type='end'
                                value={[formParams.enddate, formParams.endtime]}
                                startValue={formParams.begindate ? new Date(formParams.begindate) : null}
                                onChange={(v) => {
                                    if (taskInfo.maxSubTaskEndDate == "" || typeof (taskInfo.maxSubTaskEndDate) == "undefined") {
                                        setFormFields({ enddate__endtime: { value: v } });
                                        this.workdayComputed(v, "end")
                                    } else {
                                        if (new Date(v[0]) < new Date(taskInfo.maxSubTaskEndDate)) {
                                            // Modal.warning({
                                            //     title: getLabel(83887, "任务完成的最后时间小于其子任务完成的最后时间！"),
                                            //     content: ""
                                            // });
                                            message.error(getLabel(83887, "任务完成的最后时间小于其子任务完成的最后时间！"));
                                            setFormFields({ enddate__endtime: { value: [taskInfo.maxSubTaskEndDate, formParams.endtime] } });
                                            this.workdayComputed([taskInfo.maxSubTaskEndDate, formParams.endtime], "end")
                                        } else {
                                            setFormFields({ enddate__endtime: { value: v } });
                                            this.workdayComputed(v, "end")
                                        }
                                    }
                                }} />
                        </Col>
                    </Row>
                } else if (fields.domkey[0] == "actualbegindate") {
                    dom = <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@odnp30@${fields.domkey[0]}`}>
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@hk4dbh@${fields.domkey[0]}`} span={24} style={stylecss}>
                            <PrjDateTime ecId={`${this && this.props && this.props.ecId || ''}_PrjDateTime@4k8rtc@${fields.domkey[0]}`}
                                endValue={formParams.actualenddate ? new Date(formParams.actualenddate) : null}
                                {...fields}
                                isTimeShow={isTimeShow}
                                type='start'
                                value={[formParams.actualbegindate, formParams.actualbegintime]}
                                onChange={(v) => { setFormFields({ actualbegindate__actualbegintime: { value: v } }); this.onActualComputed(v, "begin") }} />
                        </Col>
                    </Row>
                } else if (fields.domkey[0] == "actualenddate") {
                    dom = <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@98l5oa@${fields.domkey[0]}`}>
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@i5o1t5@${fields.domkey[0]}`} span={24} style={stylecss}>
                            <PrjDateTime ecId={`${this && this.props && this.props.ecId || ''}_PrjDateTime@5uknm8`} startValue={formParams.actualbegindate ? new Date(formParams.actualbegindate) : null} {...fields}
                                isTimeShow={isTimeShow}
                                type='end'
                                value={[formParams.actualenddate, formParams.actualendtime]}
                                onChange={(v) => { setFormFields({ actualenddate__actualendtime: { value: v } }); this.onActualComputed(v, "end") }} />
                        </Col>
                    </Row>
                } else if (fields.domkey[0] == "finish") {
                    if (fields.viewAttr == "1") {
                        dom = <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@v5w2xu`}>
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@yxpfde`} span={12} style={stylecss}>
                                <WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@x5lp6k`} name={fields.domkey[0]} percent={fields.value || 0} strokeColor={fields.strokeColor} status="active" />
                            </Col><span style={{ color: "#FF0000" }}>{fields.befSpan || ""}</span>
                        </Row>
                    } else {
                        dom = <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@6yxf8i`}>
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@cc1mvy`} span={24} style={stylecss}>
                                <InputNumber ecId={`${this && this.props && this.props.ecId || ''}_InputNumber@h7m3y3`} name={fields.domkey[0]} min={0} value={formParams.finish}
                                    onChange={(v) => { this.checkProgress(v); }} />
                                <span style={{ marginLeft: 5 }}>%</span>
                            </Col>
                        </Row>
                    }
                } else if (fields.conditionType == "RICHTEXT") {   //多行文本
                    if(fields.viewAttr == "1"){
                        dom = <div className='view_basicToolBar'><WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@4ysjy5`} fieldConfig={{...fields,ckConfig:view_basicToolBar}} form={form}/></div>
                    }else{
                        dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@3ikm4k`} fieldConfig={{...fields,ckConfig:basicToolBar}} form={form}/>
                    }
                } else if (fields.domkey[0] == "accessory") {
                    let domkey = fields.domkey[0];
                    dom = <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@xfo7mw`}>
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@590wtd`} span={24} style={stylecss}>
                            <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@g30n0b`}
                                name = {domkey}
                                uploadId={[domkey]}
                                uploadUrl={"/api/proj/prjutil/fileUpload?accsec=" + fields.accsec}
                                category={fields.accsec}
                                autoUpload={true}
                                showBatchLoad={false}
                                showClearAll={false}
                                multiSelection={true}
                                datas={toJS(fields.datas)}
                                maxUploadSize={fields.accsize}
                                onChange={v => { setFormFields({ [domkey]: { value: v } }) }}
                                viewAttr={fields.viewAttr}
                            // onUploading={(state)=>{}}
                            />
                        </Col>
                    </Row>
                } else if (fields.domkey[0] == "workday") {
                    dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@l296a4`} fieldConfig={fields} form={form} onChange={v => { this.endDateComputed(v) }} />;
                } else if (fields.domkey[0] == "realmandays") {
                    dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@6pa9lp`} fieldConfig={fields} form={form} onChange={v => { this.endActualDateComputed(v) }} />;
                } else if (fields.domkey[0] == "parentid") {
                    dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@y136ya`} fieldConfig={fields} form={form} onChange={v => { this.onParentChange(v) }} />;
                }else {
                    dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@vse05u`} fieldConfig={fields} form={form} />;
                }
                if (hasunderline) {
                    items.push({
                        com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@3vxf79@${fields.domkey[0]}`}
                            label={`${fields.label}`}
                            labelCol={{ span: `${fields.labelcol}` }}
                            error={form.getError(fields)}
                            tipPosition="bottom"
                            wrapperCol={{ span: `${fields.fieldcol}` }} underline>
                            {dom}
                        </WeaFormItem>),
                        colSpan: 1,
                        hide: hide
                    });
                } else {
                    items.push({
                        com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@zumg6p@${fields.domkey[0]}`}
                            label={`${fields.label}`}
                            labelCol={{ span: `${fields.labelcol}` }}
                            error={form.getError(fields)}
                            tipPosition="bottom"
                            wrapperCol={{ span: `${fields.fieldcol}` }} >
                            {dom}
                        </WeaFormItem>),
                        colSpan: 1,
                        hide: hide
                    });
                }

            });
            group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@w6yww2@${i}`} needTigger={true} title={c.title} col={1} showGroup={c.defaultshow} items={items} />)
        });
        return group;
    }

    workdayComputed = (arg, type) => {
        const { setFormFields, taskInfo: { passnoworktime, userid }, isTimeShow } = this.props.listStore;
        const { form } = this.props;
        const formParams = form.getFormParams() || {};
        let res = "";
        if (type == "begin") {
            if (arg[0] && formParams.enddate) {
                res = datediff(arg[0], formParams.enddate, isTimeShow=='1'?arg[1] || "00:00":"00:00", isTimeShow=='1'?formParams.endtime || "23:59":"23:59", userid, passnoworktime);
            }
        } else {
            if (arg[0] && formParams.begindate) {
                res = datediff(formParams.begindate, arg[0], isTimeShow=='1'?formParams.begintime || "00:00":"00:00", isTimeShow=='1'?arg[1] || "23:59":"23:59", userid, passnoworktime);
            }
        }
        setFormFields({ workday: { value: res } });
    }

    onActualComputed = (arg, type) => { //maxSubTaskEndDate
        const { setFormFields, taskInfo: { passnoworktime, userid }, isTimeShow } = this.props.listStore;
        const { form } = this.props;
        const formParams = form.getFormParams() || {};
        let res = "0";
        if (type == "begin") {
            if (arg[0] && formParams.actualenddate) {
                res = datediff(arg[0], formParams.actualenddate, isTimeShow=='1'?arg[1] || "00:00":"00:00", isTimeShow=='1'?formParams.actualendtime || "23:59":"23:59", userid, passnoworktime);
            }
        } else {
            if (arg[0] && formParams.actualbegindate) {
                res = datediff(formParams.actualbegindate, arg[0], isTimeShow=='1'?formParams.actualbegintime || "00:00":"00:00", isTimeShow=='1'?arg[1] || "23:59":"23:59", userid, passnoworktime);
            }
        }
        setFormFields({ realmandays: { value: res } })
    }

    endDateComputed = (value) => {
        const { setFormFields, taskInfo: { passnoworktime, userid } } = this.props.listStore;
        const { form } = this.props;
        const formParams = form.getFormParams() || {};

        let b = typeof (formParams.begindate) == "undefined" ? "" : formParams.begindate;
        let e = typeof (formParams.enddate) == "undefined" ? "" : formParams.enddate;
        let w = typeof (formParams.workday) == "undefined" ? "" : formParams.workday;
        let bt = typeof (formParams.begintime) == "undefined" ? "" : formParams.begintime;
        let et = typeof (formParams.endtime) == "undefined" ? "" : formParams.endtime;
        let res = "";
        let alldate = "";
        if (bt == "") {
            bt = "00:00";
        }
        if (et == "") {
            et = "23:59";
        }

        if (w == "" && b != "" && e != "") {
            setFormFields({ enddate: { value: "" } })
        } else if (w != "" && ((b != "" && e != "") || (b != "" && e == ""))) {
            if (w > 0) {
                if (passnoworktime != "1") {

                    alldate = this.addEndDate(b, w, bt);
                } else {

                    $.ajax({
                        type: "post",
                        url: "/proj/process/GetDateByWorkLong.jsp",
                        data: "method=getEndDate&workLong=" + w + "&begindate=" + b + "&begintime=" + bt + "&manager=" + userid,
                        dataType: "text",
                        async: false,
                        success: function (data) {
                            alldate = data.trim();
                        }
                    });
                }
                if(alldate == 'error'){
                    message.error(getLabel(84409, "一般工作时间未设置，请告知管理员！"));
                    setFormFields({ enddate__endtime: { value: [] } })
                }else{
                    let tmpesp = alldate.split(" ");
                    setFormFields({ enddate__endtime: { value: [tmpesp[0], tmpesp[1]] } })
                }
            } else {
                setFormFields({ workday: { value: "" }, enddate__endtime: { value: [] } })
            }

        } else if (w != "" && b == "" && e != "") {
            if (w > 0) {
                if (passnoworktime != "1") {

                    alldate = this.addBeginDate(e, -(w), et);
                } else {
                    $.ajax({
                        type: "post",
                        url: "/proj/process/GetDateByWorkLong.jsp",
                        data: "method=getBeginDate&workLong=" + w + "&enddate=" + e + "&endtime=" + et + "&manager=" + userid,
                        dataType: "text",
                        async: false,
                        success: function (data) {
                            alldate = data.trim();
                        }
                    });
                }
                if(alldate == 'error'){
                    message.error(getLabel(84409, "一般工作时间未设置，请告知管理员！"));
                    setFormFields({ enddate__endtime: { value: [] } })
                }else{
                    let tmpesp = alldate.split(" ");
                    setFormFields({ enddate__endtime: { value: [tmpesp[0], tmpesp[1]] } })
                }
            } else {
                setFormFields({ workday: { value: "" }, begindate__begintime: { value: [] } })
            }

        }
    }

    endActualDateComputed = (value) => {
        const { setFormFields, taskInfo: { passnoworktime, userid } } = this.props.listStore;
        const { form } = this.props;
        const formParams = form.getFormParams() || {};

        let b = typeof (formParams.actualbegindate) == "undefined" ? "" : formParams.actualbegindate;
        let e = typeof (formParams.actualenddate) == "undefined" ? "" : formParams.actualenddate;
        let w = typeof (formParams.realmandays) == "undefined" ? "" : formParams.realmandays;
        let bt = typeof (formParams.actualbegintime) == "undefined" ? "" : formParams.actualbegintime;
        let et = typeof (formParams.actualendtime) == "undefined" ? "" : formParams.actualendtime;
        let res = "";
        let alldate = "";
        if (bt == "") {
            bt = "00:00";
        }
        if (et == "") {
            et = "23:59";
        }

        if (w == "" && b != "" && e != "") {
            setFormFields({ actualenddate: { value: "" } })
        } else if (w != "" && ((b != "" && e != "") || (b != "" && e == ""))) {
            if (w > 0) {
                if (passnoworktime != "1") {

                    alldate = this.addEndDate(b, w, bt);
                } else {

                    $.ajax({
                        type: "post",
                        url: "/proj/process/GetDateByWorkLong.jsp",
                        data: "method=getEndDate&workLong=" + w + "&begindate=" + b + "&begintime=" + bt + "&manager=" + userid,
                        dataType: "text",
                        async: false,
                        success: function (data) {
                            alldate = data.trim();
                        }
                    });
                }
                if(alldate == 'error'){
                    message.error(getLabel(84409, "一般工作时间未设置，请告知管理员！"));
                    setFormFields({ actualenddate__actualendtime: { value: [] } })
                }else{
                    let tmpesp = alldate.split(" ");
                    setFormFields({ actualenddate__actualendtime: { value: [tmpesp[0], tmpesp[1]] } })
                }
            } else {
                setFormFields({ realmandays: { value: "" }, actualenddate__actualendtime: { value: [] } })
            }

        } else if (w != "" && b == "" && e != "") {
            if (w > 0) {
                if (passnoworktime != "1") {

                    alldate = this.addBeginDate(e, -(w), et);
                } else {
                    $.ajax({
                        type: "post",
                        url: "/proj/process/GetDateByWorkLong.jsp",
                        data: "method=getBeginDate&workLong=" + w + "&enddate=" + e + "&endtime=" + et + "&manager=" + userid,
                        dataType: "text",
                        async: false,
                        success: function (data) {
                            alldate = data.trim();
                        }
                    });
                }
                if(alldate == 'error'){
                    message.error(getLabel(84409, "一般工作时间未设置，请告知管理员！"));
                    setFormFields({ actualenddate__actualendtime: { value: [] } })
                }else{
                    let tmpesp = alldate.split(" ");
                    setFormFields({ actualenddate__actualendtime: { value: [tmpesp[0], tmpesp[1]] } })
                }
            } else {
                setFormFields({ realmandays: { value: "" }, actualenddate__actualendtime: { value: [] } })
            }

        }
    }

    addBeginDate = (dd, dadd, bt) => {
        let arr = dd.split("-");
        let btt = bt.split(":");
        let a = new Date(arr[0], arr[1] - 1, arr[2], btt[0], btt[1]).valueOf();
        a = (a + dadd * 24 * 60 * 60 * 1000) + 60 * 1000;
        a = new Date(a);
        return this.format(a);
    }


    addEndDate = (dd, dadd, bt) => {
        let arr = dd.split("-");
        let btt = bt.split(":");
        let a = new Date(arr[0], arr[1] - 1, arr[2], btt[0], btt[1]).valueOf();
        a = (a + dadd * 24 * 60 * 60 * 1000) - 60 * 1000;
        a = new Date(a);
        return this.format(a);
    }

    format = (date) => {
        let o = {
            "M+": date.getMonth() + 1, //month
            "d+": date.getDate(),    //day
            "h+": date.getHours(),   //hour
            "m+": date.getMinutes(), //minute
            "s+": date.getSeconds(), //second
            "q+": Math.floor((date.getMonth() + 3) / 3),  //quarter
            "S": date.getMilliseconds() //millisecond
        }
        let format = "yyyy-MM-dd hh:mm";
        if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o) if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1,
                RegExp.$1.length == 1 ? o[k] :
                    ("00" + o[k]).substr(("" + o[k]).length));
        return format;
    }

    checkProgress = (value) => {  //进度编辑校验
        const { taskInfo, setFormFields } = this.props.listStore;
        if (Number(taskInfo.finishmax) == 99) {
            if (value > 99) {
                // Modal.warning({
                //     title: getLabel(383829, "该任务所必须的相关文档或者相关流程不存在，任务不能完成100%。"),
                //     content: '',
                // });
                message.error(getLabel(383829, "该任务所必须的相关文档或者相关流程不存在，任务不能完成100%。"));
                setFormFields({ finish: { value: 99 } });
            } else {
                setFormFields({ finish: { value: value } });
            }
        } else {
            if (value > 100) {
                setFormFields({ finish: { value: 100 } });
            } else {
                setFormFields({ finish: { value: value } });
            }
        }
    }

    onParentChange = (obj) => {
        const { resetStage } = this.props.listStore;
        if(obj.parentid.value != ""){
            resetStage({viewAttr : 1},obj.parentid.value);
        }else{
            resetStage({viewAttr : 3});
        }

    } 
}

